<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\Admin;
use plugin\admin\app\model\Dict;
use plugin\admin\app\model\V1Line;
use plugin\admin\app\service\v1\OptionService;
use plugin\admin\app\service\v1\OrderNodeService;
use plugin\admin\app\service\v1\OrderService;
use plugin\admin\app\service\v1\UserRechargeService;
use plugin\admin\app\service\v1\RegionService;
use plugin\admin\app\service\v1\UserExtendService;
use plugin\admin\app\service\v1\UserLinkService;
use plugin\admin\app\service\v1\UserService;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;

/**
 * 会员端接口
 */
class V1ApiController extends Crud
{
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = [
        'getIndex',
        'getNoticeList',
        'getGameList',
        'getAreaList',
        'getIspList',
        'getIpSegmentList',
        'getOpenList',
        'getCustomTypeList',
        'getPortList',
        'getNodeExportTypeList',
        'getAverageTimeList',
        'getCustomTypeListExchange',
    ];

    /**
     * 需要登录无需权的方法
     * @var array
     */
    protected $noNeedAuth = [
        'getIndex', 'editUserInfo',
        'getLinkList', 'createLink', 'deleteLink',
        'getUserExtend', 'editUserExtend',
        'recharge',
        'getRegionList', 'createOrder',
        'orderGameList',
        'getNodeRenewDurationList', 'renew',
        'getInvitationUserList', 'transfer',
        'averageTime',
        'updatePwd',
        'getLineIds', 'getGameListExchange', 'exchange',
        'renewAutoOpen',
        'bind',
        'createRefund',
        'importMatchingData',
        'getOrderList',
        'createApi'
    ];

    /**
     * @var Admin
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = null;
    }

    /**
     * 首页信息
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function getIndex(Request $request): Response
    {
        $admin = admin();
        if ($admin['user_status'] == CommonConstant::DEFAULT_1) {
            return $this->json(1, '用户不是会员！');
        }
        $result = UserService::getIndex($admin);
        return json(['code' => 0, 'msg' => '首页信息', 'data' => $result]);
    }

    /**
     * 编辑会员信息
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function editUserInfo(Request $request): Response
    {
        $avatar = $request->input('avatar');
        $qq = $request->input('qq');
        $weixin = $request->input('weixin');
        $params = [];
        if ($avatar) {
            $params['avatar'] = $avatar;
        }
        if ($qq) {
            $params['qq'] = $qq;
        }
        if ($weixin) {
            $params['weixin'] = $weixin;
        }
        if (!$params) {
            return $this->json(0, '修改成功');
        }
        $admin = admin();
        Admin::where('id', $admin['id'])->update($params);
        return $this->json(0, '修改成功');
    }


    /**
     * 推广链接列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getLinkList(Request $request): Response
    {
        $admin = admin();
        $result = UserLinkService::select($admin);
        return $this->json(0, '推广链接列表', $result);
    }

    /**
     * 添加/编辑推广链接
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function createLink(Request $request): Response
    {
        $id = $request->input('id');
        $remark = $request->input('remark');
        $data = $request->input('data');
        $data = is_string($data) ? json_decode($data, true) : $data;
        $params = compact('remark', 'data');
        $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
        if ($validate['code']) {
            return json($validate);
        }
        $admin = admin();
        UserLinkService::create($id, $params, $admin);
        return $this->json(0, $id > 0 ? '编辑成功' : '添加成功');
    }

    /**
     * 删除推广链接
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function deleteLink(Request $request): Response
    {
        $id = $request->input('id');
        if (!$id) {
            return $this->json(1, '推广链接参数错误！');
        }
        $params = [];
        $admin = admin();
        UserLinkService::delete($id, $params, $admin);
        return $this->json(0, '删除成功');
    }


    /**
     * 指定会员的推广权限
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getUserExtend(Request $request): Response
    {
        $type = $request->input('type');
        $user_id = $request->input('user_id');
        if ($type != 2) {
            if (!$user_id) {
                return $this->json(1, '会员参数错误！');
            }
        }
        $admin = admin();
        list($parent_user_extend, $user_extend, $line_column, $user) = UserExtendService::getUserExtendParent($user_id, $admin, $type);
        $data = compact('parent_user_extend', 'user_extend');
        return $this->json(0, '指定会员的推广权限', $data);
    }

    /**
     * 编辑会员推广权限
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function editUserExtend(Request $request): Response
    {
        $user_id = $request->input('user_id');
        $data = $request->input('data');
        $data = is_string($data) ? json_decode($data, true) : $data;
        $params = compact('user_id', 'data');
        $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
        if ($validate['code']) {
            return json($validate);
        }
        $admin = admin();
        UserExtendService::edit($params, $admin);
        return $this->json(0, '编辑成功');
    }


    /**
     * 充值
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function recharge(Request $request): Response
    {
        $pay_type = $request->input('pay_type');
        $amount = $request->input('amount');
        $code = $request->input('code');
        $params = compact('pay_type', 'amount', 'code');
        $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
        if ($validate['code']) {
            return json($validate);
        }
        $params = $validate['data'];
        $admin = admin();
        if ($admin['user_status'] == CommonConstant::DEFAULT_1) {
            return $this->json(1, '用户不是会员！');
        }
        $result = UserRechargeService::recharge($params, $admin);
        return json($result);
    }


    /**
     * 公告列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function getNoticeList(Request $request): Response
    {
        $list = (array)Util::db()->table('wa_v1_notice')
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
        return $this->json(0, '公告列表', $list);
    }

    // 购买节点

    /**
     * 游戏列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getGameList(Request $request): Response
    {
        $letter = $request->input('letter');
        $name = $request->input('name');
        $list = Util::db()->table('wa_v1_game')
            ->where('deleted', CommonConstant::DELETE_0)
            ->when('letter', function ($query) use ($letter) {
                if ($letter) {
                    $query->where('letter', $letter);
                }
            })
            ->when('name', function ($query) use ($name) {
                if ($name) {
                    $query->where('name', 'like', '%' . $name . '%');
                }
            })
            ->select(['id', 'name', 'id as value'])
            ->orderBy('letter', 'asc')
            ->get();
        return json(['code' => 0, 'msg' => '游戏列表', 'data' => $list]);
    }

    /**
     * 省份列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getAreaList(Request $request): Response
    {
        $list = Util::db()->table('wa_v1_region_area')
            ->orderBy('id', 'asc')
            ->get();
        return json(['code' => 0, 'msg' => '省份列表', 'data' => $list]);
    }

    /**
     * ISP列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getIspList(Request $request): Response
    {
        $line_id = (integer)$request->input('line_id', 0);
        if (!$line_id) {
            return $this->json(0, 'ISP列表！', []);
        }
        $list = Util::db()->table('wa_v1_region_operator')
            ->where('deleted', CommonConstant::DELETE_0)
            ->where('line_id', $line_id)
            ->orderBy('id', 'desc')
            ->get();
        return json(['code' => 0, 'msg' => 'ISP列表', 'data' => $list]);
    }

    /**
     * IP段列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getIpSegmentList(Request $request): Response
    {
        return $this->json(0, 'IP段列表', Dict::getNew('get_ip_segment_list'));
    }

    /**
     * 可开地区列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getOpenList(Request $request): Response
    {
        return $this->json(0, '可开地区列表', Dict::getNew('get_open_list'));
    }

    /**
     * 自定义账号列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getCustomTypeList(Request $request): Response
    {
        return $this->json(0, '自定义账号列表', Dict::getNew('get_custom_type_list'));
    }

    /**
     * 自选端口列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getPortList(Request $request): Response
    {
        return $this->json(0, '自选端口列表', []);
    }

    /**
     * 地区列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getRegionList(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $game_id = (integer)$request->input('game_id', 0);
            $area_id = (integer)$request->input('area_id', 0);
            $operator_id = (integer)$request->input('operator_id', 0);
            $ip_segment = (integer)$request->input('ip_segment', 0);
            $open = (integer)$request->input('open', 0);
            $params = compact('line_id', 'game_id');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $result = RegionService::select($line_id, $game_id, $area_id, $operator_id, $ip_segment, $open);
            return json(['code' => 0, 'msg' => '地区节点列表', 'data' => $result]);
        }
    }

    /**
     * 购买
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function createOrder(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $game_id = (integer)$request->input('game_id', 0);
            $ip_segment = (integer)$request->input('ip_segment', 0);
            $duration = $request->input('duration', '');
            $custom_type = (integer)$request->input('custom_type', 0);
            $account = $request->input('account', '');
            $pass = $request->input('pass', '');
            $group = (integer)$request->input('group_name', 0);
            $remark = $request->input('remark', '');
            $port = $request->input('port', '');
            $data = $request->input('data');
            $data = is_array($data) ? $data : json_decode($data, true);
            $params = compact('line_id', 'game_id', 'ip_segment', 'duration', 'custom_type', 'account', 'pass', 'group', 'remark', 'port', 'data');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $lock = Util::basicSetnx(__FUNCTION__);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $admin = admin();
            $result = OrderService::create($params, $admin);
            return json($result);
        }
    }

    // 所有订单

    /**
     * 购买项目列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function orderGameList(Request $request): Response
    {
        $admin = admin();
        if ($admin['user_status'] != CommonConstant::DEFAULT_2) {
            return json(['code' => 0, 'msg' => '购买项目列表', 'data' => []]);
        }

        $db = Util::db();
        // 取订单的所有游戏ID groupBy来去重
        $all = $db->table('wa_v1_order')
            ->where('deleted', CommonConstant::DELETE_0)
            ->where('user_id', $admin['id'])
            ->groupBy('game_id')
            ->pluck('game_id')
            ->toArray();
        $list = [];
        if ($all) {
            $list = $db->table('wa_v1_game')
                ->whereIn('id', $all)
                ->select(['id', 'name', 'id as value'])
                ->orderBy('id', 'desc')
                ->get();
        }
        return json(['code' => 0, 'msg' => '购买项目列表', 'count' => count($list), 'data' => $list]);
    }

    // 所有节点

    /**
     * 节点导出格式列表
     **/
    public function getNodeExportTypeList(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $list = Util::db()->table('wa_v1_node_export_type')->get();
            return json(['code' => 0, 'msg' => '节点导出格式列表', 'data' => $list]);
        }
    }

    /**
     * 续费时间列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getNodeRenewDurationList(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $params = compact('line_id');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $result = OrderNodeService::getNodeRenewDurationList($line_id, $admin, $user);
            return $this->json(0, '续费时间列表', $result);
        }
    }

    /**
     * 续费
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function renew(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $duration = $request->input('duration', '');
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $params = compact('line_id', 'duration', 'ids');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lock = Util::basicSetnx(__FUNCTION__, 3);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $result = OrderNodeService::renew($params, $admin, $user);
            return json($result);
        }
    }

    /**
     * 搜索下级会员列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getInvitationUserList(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $username = $request->input('username', '');
            $params = compact('username');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $result = UserService::getInvitationUserList($params, $admin, $user);
            return json(['code' => 0, 'msg' => '搜索下级会员列表', 'data' => $result]);
        }
    }

    /**
     * 过户
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function transfer(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $to_user_id = (integer)$request->input('to_user_id', 0);
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $params = compact('line_id', 'to_user_id', 'ids');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lock = Util::basicSetnx(__FUNCTION__, 3);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            OrderNodeService::transfer($params, $admin, $user);
            return json(['code' => 0, 'msg' => '过户成功', 'data' => []]);
        }
    }

    /**
     * 平均时间列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getAverageTimeList(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return $this->json(0, '平均时间列表', OptionService::getConfigAvgData());
        }
    }

    /**
     * 平均时间
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function averageTime(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $date = $request->input('date', '');
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $params = compact('line_id', 'date', 'ids');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lock = Util::basicSetnx('renew', 3);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $result = OrderNodeService::averageTime($params, $admin, $user);
            return json($result);
        }
    }

    /**
     * 修改密码
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function updatePwd(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $type = (integer)$request->input('type', 0);
            $data = $request->input('data');
            $data = is_array($data) ? $data : json_decode($data, true);
            $password = $request->input('password', '');
            $params = compact('line_id', 'type', 'data', 'password');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lock = Util::basicSetnx('transfer', 3);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $result = OrderNodeService::updatePwd($params, $admin, $user);
            return json($result);
        }
    }

    /**
     * 调换-自定义账号列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getCustomTypeListExchange(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return $this->json(0, '调换-自定义账号列表', Dict::getNew('get_custom_type_list_exchange'));
        }
    }

    /**
     * 调换-跨线路列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getLineIds(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            if (!$line_id) {
                return $this->json(1, '线路参数错误！');
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lineInfo = V1Line::where('deleted', CommonConstant::DELETE_0)
                ->where('id', $line_id)
                ->select(['id', 'name', 'line_ids'])
                ->first();
            if (!$lineInfo) {
                return $this->json(1, '线路配置错误！');
            }
            if ($line_id == $lineInfo->line_ids) {
                $list = [$lineInfo->toArray()];
            } else {
                $line_ids = explode(',', $lineInfo->line_ids);
                $list = V1Line::where('deleted', CommonConstant::DELETE_0)
                    ->whereIn('id', $line_ids)
                    ->select(['id', 'name'])
                    ->orderBy('weight', 'desc')
                    ->get()
                    ->toArray();
            }
            $exchange_user_list = OrderService::orderNumber($user, CommonConstant::DEFAULT_4);
            $exchange_user_list = array_column($exchange_user_list, null, 'line_id');
            $line_column = $list ? array_column($list, null, 'id') : [];
            $userExtend = UserExtendService::getUserExtend($line_column, $user);
            $userExtend = UserExtendService::addNameToExtend($line_column, $userExtend, $exchange_user_list);
            $list = $userExtend;
            return json(['code' => 0, 'msg' => '调换-跨线路列表', 'data' => $list]);
        }
    }

    /**
     * 调换-游戏可售列表（废弃）
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getGameListExchange(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $params = compact('line_id', 'ids');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $result = OrderNodeService::getGameListExchange($params, $admin, $user);
            return json(['code' => 0, 'msg' => '游戏可售列表', 'data' => $result]);
        }
    }

    /**
     * 调换
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function exchange(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $type = (integer)$request->input('type', 0);
            $account_type = (integer)$request->input('account_type', 0);
            $account = $request->input('account', '');
            $pass = $request->input('pass', '');
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $data = $request->input('data');
            if ($type == CommonConstant::DEFAULT_3) {
                $data = is_array($data) ? $data : json_decode($data, true);
            }
            $game_id = (integer)$request->input('game_id', 0);
            $line_id_new = (integer)$request->input('line_id_new', 0);
            $params = compact('line_id', 'type', 'account_type', 'account', 'pass', 'ids', 'data', 'game_id', 'line_id_new');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lock = Util::basicSetnx('createOrder');
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $result = OrderNodeService::exchange($params, $admin, $user);
            return json($result);
        }
    }

    /**
     * 自动续费开启/关闭
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function renewAutoOpen(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $status = $request->input('status');
            $params = compact('ids', 'status');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            OrderNodeService::renewAutoOpen($params, $admin, $user);
            return json(['code' => 0, 'msg' => $status == CommonConstant::DEFAULT_1 ? '开启成功！' : '关闭成功！', 'data' => []]);
        }
    }

    /**
     * 解绑
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function bind(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $params = compact('ids');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $lock = Util::basicSetnx('renew', 3);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $result = OrderNodeService::bind($params, $admin, $user);
            return json($result);
        }
    }

    /**
     * 申请退款
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function createRefund(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $ids = $request->input('ids');
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            $params = compact('line_id', 'ids');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }

            $lock = Util::basicSetnx(__FUNCTION__, 3);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $admin = admin();
            OrderNodeService::createRefund($params, $admin);
            return json(['code' => 0, 'msg' => '退款申请成功，请耐心等待审核！', 'data' => []]);
        }
    }

    // 导入（续费/改密）

    /**
     * 导入匹配订单节点
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function importMatchingData(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $line_id = (integer)$request->input('line_id', 0);
            $is_expire = (integer)$request->input('is_expire', 0); // 只显示过期数据:0=否,1=是
            $content = $request->input('content', '');
            $params = compact('line_id', 'is_expire', 'content');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }
            $params = $validate['data'];

            $user_id = (integer)$request->input('user_id', 0);
            $admin = admin();
            $validateUserStatus = Util::validateUserStatus($user_id, $admin);
            if ($validateUserStatus['code']) {
                return json($validateUserStatus);
            }
            $user = $validateUserStatus['data'];

            $result = OrderNodeService::importMatchingData($params, $admin, $user);
            return json(['code' => 0, 'msg' => '导入匹配订单节点', 'data' => $result]);
        }
    }

    // IP黑名单

    // API提取
    /**
     * API提取-订单列表
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function getOrderList(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $admin = admin();
        $result = OrderNodeService::getOrderList($page, $limit, $admin);
        return json($result);
    }

    /**
     * API提取-生成
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function createApi(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $order_ids = $request->input('order_ids');// 订单Ids
            $order_ids = is_array($order_ids) ? $order_ids : explode(',', $order_ids);
            $format = (integer)$request->input('format', 0); // 返回格式:1=txt,2=json
            $line = (integer)$request->input('line', 0); // 行分隔符:1=\r\n,2=\n,3=空格分割,4=自定义
            $custom_line = $request->input('custom_line', ''); // 自定义分隔符
            $output = (integer)$request->input('output', 0); // 输出样式定制:1=skt5,2=http
            $expire_time = (integer)$request->input('expire_time', 0); // Token有效时间(天)
            $params = compact('order_ids', 'format', 'line', 'custom_line', 'output', 'expire_time');
            $validate = Util::validateParams('v1-api', __FUNCTION__, $params);
            if ($validate['code']) {
                return json($validate);
            }
            $host = $request->host();
            $admin = admin();
            $result = OrderNodeService::createApi($params, $host, $admin);
            return json(['code' => 0, 'msg' => '生成API', 'data' => $result]);
        }
    }

}
